import React from 'react'
import {
    Form,
    Input,
    Button,
    Icon,
    message,
    Upload,
    Progress
} from 'antd';
import { connect } from 'dva';
import { UrlConfig } from '../../../services/fetch';
import { getBase64, beforeImgUpload, beforeVideoUpload } from '../../../utils/request';

const FormItem = Form.Item;

@connect(({ video }) => ({
    video,
}))
@Form.create()
export default class AddModal extends React.PureComponent {

    constructor(props) {
        super(props);

        this.state = {
            loading: false,
            videoError: false,
            imgError: false,
            loadingVideo: false,
            VideoUrl: '',
            imageUrl: '',
            percentVideo: 0,
            percentImage: 0,
            currentHive: '',
        }

        // //初始化内容库插件
        // this.bar = window.sBar({
        //     //插件地址
        //     requestUrl: "http://birtv.sobey.com:19207",
        //     // 验证token
        //     token: 'c9f646a7455636049fdeb89cfa244766',
        //     // 站点code
        //     siteCode: 'S1',
        //     // 用户code
        //     userCode: '365c0a1a129344388cfc8d2030d5179b',

        //     //显示功能导航条  公共素材(ggsc)、个人素材(grsc)、关联素材(glsc)
        //     navCode: ['ggsc'],
        //     //首次加载默认导航条数据
        //     //activeNavCode:"ggsc",
        //     //侧边栏距离顶部间距
        //     //offsetTop: 40,

        //     //插件放在传入指定容器中，参数为容器id
        //     //containerId:"cid",
        //     //插件收起状态下是否显示展开按钮, true:显示，false：不显示
        //     //showBarButton: true,
        //     //侧边栏是否处于展开状态
        //     //isExpand:true

        //     //使用素材时的回调函数，这儿定义后，后面的on监听事件则会无效
        //     callback: (data) => {
        //         this.hiveCallback(data);
        //     }
        // }).create();

    }

    componentDidMount() {

        //订阅
        window.PubSub.subscribe('addModal', () => {
            this.setState({
                VideoUrl: '',
                imageUrl: '',
                percentVideo: 0,
                percentImage: 0,
            })
            this.props.form.resetFields();
        });

        this.props.callback(this);

    }

    handleCancel = () => {
        this.bar.hide();
    }

    /**
     * 图片上传回调
     */
    handleImgChange = (info) => {
        if (info.file.status == 'error') {
            this.setState({ imgError: true });
        }
        if (info.event) {
            this.setState({ percentImage: Math.ceil(info.event.percent) })
        }
        if (info.file.status === 'uploading') {
            this.setState({ loading: true, imgError: false, });
            return;
        }
        if (info.file.status === 'done') {
            getBase64(info.file.originFileObj, imageUrl => this.setState({
                imageUrl,
                loading: false,
                imgError: false,
            }));
        }
    }

    /**
     * 视频上传回调
     */
    handleVideoChange = (info) => {
        if (info.file.status == 'error') {
            this.setState({ videoError: true });
        }
        if (info.event) {
            this.setState({ percentVideo: Math.ceil(info.event.percent) })
        }
        if (info.file.status === 'uploading') {
            this.setState({ loadingVideo: true, videoError: false, });
            return;
        }
        if (info.file.status === 'done') {
            this.setState({
                VideoUrl: info.file.response.data.video_path,
                imageUrl: this.state.imageUrl == '' ? info.file.response.data.img_path : this.state.imageUrl,
                loadingVideo: false,
                videoError: false
            })
        }
    }
    hive = (type) => {
        this.setState({
            currentHive: type
        })
        this.bar.show()
    }

    /**
     * hive插件回调
     */
    hiveCallback = (data) => {
        if (data.type == 'biz_sobey_picture') { //图片
            this.setState({
                imageUrl: data.keyFrameUrl
            })
        } else if (data.type == 'biz_sobey_video') {
            if (data.streamingUrl == '') {
                message.error('当前素材不可用');
                return false;
            } else {
                if (this.state.imageUrl == '') {
                    this.setState({
                        imageUrl: data.keyFrameUrl
                    })
                }
                this.setState({
                    VideoUrl: data.streamingUrl
                })
            }
        }else{
            message.error('请选择正确的素材类型!');
        }
    }

    /**
     * 提交
     */
    handleSubmit = (e) => {
        const { dispatch, form } = this.props;
        e.preventDefault();
        form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                if (this.state.imageUrl == '' || this.state.VideoUrl == '') {
                    message.error('视频不能为空');
                    return;
                }
                values.video_img = this.state.imageUrl;
                values.table_name = this.props.video.initTableName;
                values.video_src = this.state.VideoUrl;
                values.video_img = this.state.imageUrl;
                this.props.dispatch({
                    type: 'video/addVideo',
                    callback:()=>{
                        this.bar.hide()
                    },
                    data: values
                })
            
            }
        });
    };

    render() {


        const {
            form: { getFieldDecorator },
        } = this.props;

        const { submitting } = this.props.video;

        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 7 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 12 },
                md: { span: 10 },
            },
        };

        const submitFormLayout = {
            wrapperCol: {
                xs: { span: 24, offset: 0 },
                sm: { span: 10, offset: 7 },
            },
        };


        const uploadButton = () => {
            let text = '点击此处上传';
            if (this.state.loading) {
                text = '上传中...'
            }
            if (this.state.imgError) {
                text = '上传出错,请从新上传';
            }
            return (
                <div>
                    <Icon type={this.state.loading ? 'loading' : 'plus'} />
                    <div className="ant-upload-text">{text}</div>
                </div>
            );
        }

        const uploadVideoButton = () => {
            let text = '点击此处上传';
            if (this.state.loadingVideo) {
                text = '上传中...'
            }
            if (this.state.videoError) {
                text = '上传出错,请从新上传';
            }
            return (
                <div>
                    <Icon type={this.state.loadingVideo ? 'loading' : 'plus'} />
                    <div className="ant-upload-text">{text}</div>
                </div>
            );
        }
        const { imageUrl, VideoUrl } = this.state;

        const videoProps = {
            name: "video",
            listType: "picture-card",
            className: "avatar-uploader",
            showUploadList: false,
            action: `${UrlConfig}/fcvideo/Video/uploadVideo`,
            beforeUpload: (file) => {
                return beforeVideoUpload(file, this.state.loadingVideo)
            },
            onChange: this.handleVideoChange
        }

        const videoBtnProps = {
            name: "video",
            showUploadList: false,
            action: `${UrlConfig}/fcvideo/Video/uploadVideo`,
            beforeUpload: (file) => {
                return beforeVideoUpload(file, this.state.loadingVideo)
            },
            onChange: this.handleVideoChange
        }

        return (
            <Form onSubmit={this.handleSubmit} hideRequiredMark style={{ marginTop: 8 }}>
                <FormItem {...formItemLayout} label="标题">
                    {getFieldDecorator('video_title', {
                        rules: [
                            {
                                required: true,
                                message: '请输入标题',
                            },
                        ],
                    })(<Input placeholder="给视频起个名字" />)}
                </FormItem>
                <FormItem {...formItemLayout} label="来源">
                    {getFieldDecorator('resource')(<Input placeholder="是来自哪里呢？" />)}
                </FormItem>
                <FormItem {...formItemLayout} label="所属矩阵号">
                    {getFieldDecorator('matrix_id')(<Input placeholder="属于哪个矩阵号？" />)}
                </FormItem>
                <FormItem {...formItemLayout} label="播放数">
                    {getFieldDecorator('scan_num')(<Input placeholder="可以手动输入播放数哦~" />)}
                </FormItem>
                <FormItem {...formItemLayout} label="转发数">
                    {getFieldDecorator('forward_num')(<Input placeholder="可以手动输入转发数哦~" />)}
                </FormItem>
                <FormItem {...formItemLayout} label="上传封面图">
                    <Upload
                        name="img"
                        listType="picture-card"
                        className="avatar-uploader"
                        showUploadList={false}
                        action={`${UrlConfig}/fcvideo/Video/uploadImg`}
                        beforeUpload={(file) => {
                            return beforeImgUpload(file, this.state.loading)
                        }}
                        onChange={this.handleImgChange}
                    >
                        {imageUrl && !this.state.loading ? <img src={imageUrl} className="video_pic" alt="封面图" /> : uploadButton()}
                    </Upload>
                    {this.state.percentImage > 0 && !this.state.imgError ? <Progress percent={this.state.percentImage} status={this.state.percentImage == 100 ? 'success' : 'active'} /> : ''}
                    {this.state.imgError ? <Progress percent={this.state.percentImage} status="exception" /> : ''}
                    <Button onClick={() => {
                        this.hive('img')
                    }}>从hive内容库选择</Button>
                </FormItem>
                <FormItem {...formItemLayout} label="记者">
                    {getFieldDecorator('reporter', {
                        rules: [
                            {
                                required: true,
                                message: '请输入记者姓名',
                            },
                        ],
                    })(<Input placeholder="谁去采访的呢？" />)}
                </FormItem>
                <FormItem {...formItemLayout} label="编辑">
                    {getFieldDecorator('editor', {
                        rules: [
                            {
                                required: true,
                                message: '请输入编辑姓名',
                            },
                        ],
                    })(<Input placeholder="勤劳的编辑" />)}
                </FormItem>
                <FormItem {...formItemLayout} label="上传视频">
                    <Upload
                        className="Upload"
                        {...videoProps}
                    >
                        {VideoUrl && !this.state.loadingVideo ?
                            <video className="video_pic" src={VideoUrl} controls="controls">
                                您的浏览器不支持 video 标签。
                  </video>
                            : uploadVideoButton()}
                    </Upload>
                    {this.state.percentVideo && !this.state.videoError > 0 ? <Progress percent={this.state.percentVideo} status={this.state.percentVideo == 100 ? 'success' : 'active'} /> : ''}
                    {this.state.videoError ? <Progress percent={this.state.percentVideo} status="exception" /> : ''}
                    <Upload
                        {...videoBtnProps}
                    >
                        <Button style={{ marginRight: 20 }} ><Icon type="upload" />本地上传</Button>
                    </Upload>
                    <Button onClick={() => {
                        this.hive('video')
                    }}>从hive内容库选择</Button>
                </FormItem>

                <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
                    <Button type="primary" htmlType="submit" loading={submitting}>
                        提交
                    </Button>
                    <Button style={{ marginLeft: 8 }} onClick={() => {
                        this.props.dispatch({
                            type: 'video/hideModal'
                        })
                    }}>取消</Button>
                </FormItem>
            </Form>
        )
    }
}